package ngocthien.game;

import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.BoundCamera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.constants.Constants;
import org.anddev.andengine.util.path.astar.AStarPathFinder;

import android.content.pm.ActivityInfo;
import android.opengl.GLU;

public class StateGame extends BaseGameActivity implements IOnSceneTouchListener {

    private static BoundCamera mBoundChaseCamera;
    private static BitmapTextureAtlas mPlayerTexture;
    private static BitmapTextureAtlas mControlTexture;
    private static TextureRegion mBaseControlTextureRegion;
    private static TextureRegion mKnobControlTextureRegion;

    private static TMXLoader mTMXLoader;
    protected static boolean mUpdate;
    protected static boolean mLoading;
    protected static AnimatedSprite player;
    protected static float[] playerFootCoordinates;
    protected static TMXLayer TMXMapLayer;
    protected static TMXTile playerLocationTile;
    protected static TMXTiledMap mTMXTileMap;
    private static boolean TouchOne;
    protected static int mCurrentMapIndex;
    protected static org.anddev.andengine.util.path.Path A_path;
    protected static AStarPathFinder<TMXLayer> finder;
    protected static Path mCurrentPath;

    protected static List<TMXTile> ExitTiles;

    public Engine onLoadEngine() {
        // TODO Auto-generated method stub
        this.mBoundChaseCamera = new BoundCamera(0, 0, Global.CAMERA_WIDTH, Global.CAMERA_HEIGHT) {

            private void onApplySceceMatrix(GL10 pGL) {
                // TODO Auto-generated method stub
                GLHelper.setProjectionIdentityMatrix(pGL);
                GLU.gluOrtho2D(pGL, this.getMinX(), this.getMaxX(), this.getMaxX(), this.getMaxY());

            }
        };

        getApplicationContext();

        final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE,
                new RatioResolutionPolicy(Global.CAMERA_WIDTH, Global.CAMERA_HEIGHT), this.mBoundChaseCamera);

        engineOptions.getTouchOptions().setRunOnUpdateThread(true);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Engine engine = new Engine(engineOptions);
        return engine;
    }

    public void onLoadResources() {
        // TODO Auto-generated method stub
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

        Global.mBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        Global.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
                Global.mBackgroundTexture, this, "background.png", 0, 0);

        StateGame.mPlayerTexture = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT);
        BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mPlayerTexture, getApplicationContext(),
                "player.png", 0, 0, 3, 4);

        StateGame.mControlTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        StateGame.mBaseControlTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
                StateGame.mControlTexture, getApplicationContext(), "basecontrol.png", 0, 0);
        StateGame.mKnobControlTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
                StateGame.mControlTexture, getApplicationContext(), "knobcontrol.png", 128, 0);

        this.mEngine.getTextureManager().loadTextures(Global.mBackgroundTexture, StateGame.mControlTexture,
                StateGame.mPlayerTexture);
    }

    public Scene onLoadScene() {
        // TODO Auto-generated method stub
        this.mEngine.registerUpdateHandler(new FPSLogger());

        Global.mMainScene = new Scene();
        Global.mMainScene.setBackground(new ColorBackground(1f, 0f, 0f));

        StateGame.mTMXLoader = new TMXLoader(this, this.mEngine.getTextureManager(), TextureOptions.NEAREST, null);
        new Sprite(0, 0, mBaseControlTextureRegion);

        Global.mMainScene.registerUpdateHandler(new IUpdateHandler() {

            public void reset() {
                // TODO Auto-generated method stub

            }

            public void onUpdate(float pSecondsElapsed) {
                // TODO Auto-generated method stub

                // cho phep tiles lay vi tri nguoi choi som nhat co the
                if (mUpdate) {
                    // Get the scene-coordinates of the tile center.
                    playerFootCoordinates = player.convertLocalToSceneCoordinates(16, 16);

                    // Get the tile where the center of the current tile is.
                    playerLocationTile = TMXMapLayer.getTMXTileAt(playerFootCoordinates[Constants.VERTEX_INDEX_X],
                            playerFootCoordinates[Constants.VERTEX_INDEX_Y]);
                }

                if (!mLoading) {
                    mCurrentMapIndex = Integer.parseInt(mTMXTileMap.getTMXTiledMapProperties().get(0).getValue());
                    // TMXMapUpdater.updateTMXMap();
                }

            }
        });

        if (StateOption.TouchEnabled) {
            Global.mMainScene.setOnSceneTouchListener(this);
        }

        return Global.mMainScene;
    }

    public void onLoadComplete() {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see
     * org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener#onSceneTouchEvent(org.anddev.andengine.entity.scene
     * .Scene, org.anddev.andengine.input.touch.TouchEvent)
     */
    public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		if (!mLoading) {
			if (pSceneTouchEvent.isActionDown()
					&& pSceneTouchEvent.getX() < TMXMapLayer.getWidth()
					&& pSceneTouchEvent.getY() < TMXMapLayer.getHeight()
					&& pSceneTouchEvent.getX() > 0
					&& pSceneTouchEvent.getY() > 0 && TouchOne) {

//				UI.walkTo(pSceneTouchEvent.getX(), pSceneTouchEvent.getY(),
//						pScene);

				TouchOne = false;
				return true;
			}

		}
		return false;
	}
}
